class Solution(object):
    #heap pop的实现是通过将最大的取出，然后让最后一个值放到root上，然后max_heapify
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        from heapq import *
        counts = dict()
        for num in nums:
            if num in counts.keys():
                counts[num] += 1
            else:
                counts[num] = 1
        heap = []
        for value, count in counts.items():
            heappush(heap, (-count, value))
        res = []
        for i in range(k):
            count, value = heappop(heap)
            res.append(value)
        return res




class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        res = dict()
        for num in nums:
            if num in res:
                res[num] += 1
            else:
                res[num] = 1
        top = []
        import heapq
        for key, value in res.items():
            heapq.heappush(top, [value, key])
            if len(top) > k:
                heapq.heappop(top)
        # print(top)
        res = []
        for i in range(len(top)):
            res.append(top[i][1])
        return res